/*
 * AddInvntoryItemD.java
 *
 * Created on 09/10/2009, 5:24:38 PM
 */
package scms;

import java.awt.*;
import javax.swing.table.*;

/**
 * Gui for adding, edditing and viewing products and inventory
 * @author pumped
 */
public class AddItem extends javax.swing.JDialog {

	DefaultTableModel partsTable = new DefaultTableModel();
	Inventory inventory;
	private int inventoryID;
	private int productID;
	private boolean add = false;
	private boolean edit = true;
	private int id;
	private ScmsGuiMenu parent;

	/**
	 * default constuctor
	 * @param parent
	 * @param modal
	 */
	public AddItem(java.awt.Frame parent, boolean modal) {
		super(parent, modal);
		initComponents();

	}

	/**
	 * constructor for creating new
	 * @param parent
	 * @param inventory current inventory
	 */
	public AddItem(ScmsGuiMenu parent, Inventory inventory) {
		super((Frame) parent, false);
		initComponents();
		this.parent = parent;
		this.inventory = inventory;
		this.add = true;
		hideErrors();

		populateParts();
		inventoryID = inventory.nextInventoryID();
		txtID.setText(Integer.toString(inventoryID));
	}

	/**
	 * constructor for view/edit
	 * @param parent
	 * @param inventory current inventory
	 * @param edit boolean sets whether editing is enabled
	 * @param id id of current product
	 * @param type product or inventory
	 */
	public AddItem(ScmsGuiMenu parent, Inventory inventory, boolean edit, int id, boolean type) {
		super((Frame) parent, false);
		initComponents();
		this.parent = parent;
		this.inventory = inventory;
		this.id = id;
		this.edit = edit;
		hideErrors();

		if (type == true) {
			inventoryID = id;
		} else {
			inventoryID = inventory.getProductByID(id).getItem().getID();
			productID = id;
		}

		populateParts();
		populateFields(type);
		makeEditable(edit);
		cbProduct.setVisible(false);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        txtID = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        spQuality = new javax.swing.JSpinner();
        spQuantity = new javax.swing.JSpinner();
        jScrollPane1 = new javax.swing.JScrollPane();
        taDescription = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        cbProduct = new javax.swing.JCheckBox();
        btnAdd = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        errID = new javax.swing.JLabel();
        errName = new javax.swing.JLabel();
        cmbPart = new javax.swing.JComboBox();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblParts = new javax.swing.JTable();
        btnRemove = new javax.swing.JButton();
        btnAddPart = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("New Product/Inventory Item");

        txtID.setEditable(false);

        taDescription.setColumns(20);
        taDescription.setRows(5);
        jScrollPane1.setViewportView(taDescription);

        jLabel1.setText("ID");

        jLabel2.setText("Name");

        jLabel3.setText("Description");

        jLabel4.setText("Quality");

        jLabel5.setText("Quantity");

        cbProduct.setText("Add as Product?");
        cbProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbProductActionPerformed(evt);
            }
        });

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        errID.setForeground(new java.awt.Color(255, 0, 0));
        errID.setText("Invalid ID");

        errName.setForeground(new java.awt.Color(255, 0, 0));
        errName.setText("Invalid Name");

        tblParts.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Item", "Amount"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(tblParts);

        btnRemove.setText("Remove");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        btnAddPart.setText("Add Part");
        btnAddPart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddPartActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(errID))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(errName))
                            .addComponent(spQuality, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(spQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel5)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
                    .addComponent(cmbPart, 0, 338, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
                    .addComponent(cbProduct)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAddPart)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemove)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(errID))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(errName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spQuality, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(spQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(cmbPart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRemove)
                    .addComponent(btnAddPart))
                .addGap(18, 18, 18)
                .addComponent(cbProduct)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	/**
	 * populates parts table
	 */
	private void populateParts() {
		partsTable.addColumn("ID");
		partsTable.addColumn("Item");
		partsTable.addColumn("Description");
		partsTable.addColumn("Amount");
		tblParts.setModel(partsTable);

		for (InventoryItem i : inventory.getInventory()) {
			cmbPart.addItem(i.getID() + " - " + i.getName());
		}
	}

	/**
	 * populates form fields
	 * @param type product or inventory
	 */
	private void populateFields(boolean type) {
		InventoryItem item;
		if (type == true) {
			item = inventory.getItemByID(id);
		} else {
			item = inventory.getProductByID(id).getItem();
		}

		txtID.setText(Integer.toString(id));
		txtName.setText(item.getName());
		spQuality.setValue(item.getQuality());
		spQuantity.setValue(item.getQuantity());
		taDescription.setText(item.getDescription());

		//add parts
		for (Part p : inventory.getItemByID(inventoryID).getParts()) {
			partsTable.addRow(new Object[]{p.item.getID(), p.item.getName(), p.item.getDescription(), p.amount});
		}
	}

	/**
	 * closes without saving
	 * @param evt
	 */
	private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
		this.dispose();
	}//GEN-LAST:event_btnCancelActionPerformed

	/**
	 * hides form error messages
	 */
	private void hideErrors() {
		errID.setVisible(false);
		errName.setVisible(false);
	}

	/**
	 * adds item or saves and closes
	 * @param evt
	 */
	private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed

		if (edit == false) {
			makeEditable(true);
			return;
		}
		hideErrors();

		if (txtName.getText().equals("")) {
			errName.setVisible(true);
			//report no name error
			return;
		}

		InventoryItem item;

		if (add == false) {
			item = inventory.getItemByID(inventoryID);
			item.deleteParts();
		} else {
			item = new InventoryItem();
			item.setID(inventoryID);
		}

		//set values		
		item.setName(txtName.getText());
		item.setDescription(taDescription.getText());
		item.setQuality(Integer.parseInt(spQuality.getValue().toString()));
		item.setQuantity(Integer.parseInt(spQuantity.getValue().toString()));

		//add parts
		InventoryItem part;
		for (int i = 0; i < partsTable.getRowCount(); i++) {
			part = inventory.getItemByID(Integer.parseInt(partsTable.getValueAt(i, 0).toString()));
			int amount = Integer.parseInt(partsTable.getValueAt(i, 3).toString());
			item.addPart(part, amount);
		}

		//add new item
		if (add == true) {
			inventory.getInventory().add(item);
		}

		//add as product
		if (cbProduct.isSelected()) {
			Product newProduct;
			if (productID == 0) {
				newProduct = new Product();
				newProduct.setID(inventory.nextProductID());
				newProduct.setItem(item);
				inventory.getProducts().add(newProduct);
			}
		}

		parent.updateProducts();
		parent.updateInventory();
		parent.updateOrders();
		parent.updateParts();
		this.dispose();
	}//GEN-LAST:event_btnAddActionPerformed

	/**
	 * removes part from parts table
	 * @param evt
	 */
	private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
		partsTable.removeRow(tblParts.getSelectedRow());
	}//GEN-LAST:event_btnRemoveActionPerformed

	/**
	 * adds part to part table
	 * @param evt
	 */
	private void btnAddPartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddPartActionPerformed
		// TODO add your handling code here:
		int index = cmbPart.getSelectedIndex();
		int j = 0;

		for (InventoryItem i : inventory.getInventory()) {
			if (j == index) {
				partsTable.addRow(new Object[]{i.getID(), i.getName(), i.getDescription(), 1});
				return;
			}
			j++;
		}

	}//GEN-LAST:event_btnAddPartActionPerformed

	/**
	 * trigger for checkbox modified
	 * @param evt
	 */
	private void cbProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbProductActionPerformed
		if (cbProduct.isSelected()) {
			txtID.setText(Integer.toString(inventory.nextProductID()));
		} else {
			txtID.setText(Integer.toString(inventoryID));
		}
	}//GEN-LAST:event_cbProductActionPerformed

	/**
	 * validates id, returns int
	 * @param id
	 * @return int id
	 */
	private int validateID(String id) {
		final int INVALID = -1;
		int idNum;
		//validate as an integer
		try {
			idNum = Integer.parseInt(id);
		} catch (NumberFormatException nfe) {
			errID.setText("Invalid ID");
			return INVALID;
		}

		//check for unique value
		if (inventory.getItemByID(idNum) != null) {
			errID.setText("ID already Exists");
			return INVALID;
		}
		return idNum;
	}

	/**
	 * shows the window
	 * @param opt
	 */
	public void showWindow(boolean opt) {
		this.setVisible(opt);
	}

	/**
	 * makes for fields editable
	 * @param which boolean
	 */
	private void makeEditable(boolean which) {
		txtID.setEnabled(which);
		txtName.setEnabled(which);
		spQuality.setEnabled(which);
		spQuantity.setEnabled(which);
		taDescription.setEnabled(which);
		cmbPart.setEnabled(which);
		btnAddPart.setEnabled(which);
		btnRemove.setEnabled(which);
		tblParts.setEnabled(which);
		if (which == true) {
			btnAdd.setText("Save");
		} else {
			btnAdd.setText("Edit");
		}
		edit = which;
	}

	/**
	 * sets inventory
	 * @param inventory
	 */
	public void setInventory(Inventory inventory) {
		this.inventory = inventory;
	}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnAddPart;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnRemove;
    private javax.swing.JCheckBox cbProduct;
    private javax.swing.JComboBox cmbPart;
    private javax.swing.JLabel errID;
    private javax.swing.JLabel errName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JSpinner spQuality;
    private javax.swing.JSpinner spQuantity;
    private javax.swing.JTextArea taDescription;
    private javax.swing.JTable tblParts;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables
}
